package com.icetech.eom.service.ws.cust;

import com.icetech.commonbase.JsonTools;
import com.icetech.commonbase.UUIDTools;
import com.icetech.eom.domain.request.AppLoginRequest;
import com.icetech.eom.domain.response.AppLoginResponse;
import com.icetech.eom.domain.sys.User;
import com.icetech.eom.service.tx.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * app 鉴权实现
 * @author wangzw
 */
@Slf4j
@Component
public class SpringAppServer {

    private static Md5PasswordEncoder md5encoder = new Md5PasswordEncoder();
    @Autowired
    private IUserService userService;

    @Transactional(rollbackFor = Exception.class)
    public String login(String para) {
        log.info("<权限验证> 参数:{}",para);
        AppLoginRequest appLoginRequest = JsonTools.toBean(para, AppLoginRequest.class);
        User user = userService.findDeveloperByName(appLoginRequest.getUsername());
        AppLoginResponse appLoginResponse = new AppLoginResponse();
        if (Objects.isNull(user)){
            appLoginResponse.setState(1+"");
            appLoginResponse.setRetmsg("账号错误/或不可用");
            return JsonTools.toString(appLoginResponse);
        }
        if (!user.getPwd().equals(md5encoder.encodePassword(appLoginRequest.getPassword(),""))){
            appLoginResponse.setState(2+"");
            appLoginResponse.setRetmsg("账号/密码错误");
            return JsonTools.toString(appLoginResponse);
        }
        //生成令牌
        String token = UUIDTools.getUuid();
        appLoginResponse.setToken(token);
        appLoginResponse.setAppId(user.getId()+"");
        appLoginResponse.setState(0+"");
        return JsonTools.toString(appLoginResponse);
    }
}
